//DownloadFile.java
package com.ylaihui.servlet;

import org.apache.commons.io.IOUtils;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

public class DownloadFile extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取文件名
        String filename = req.getParameter("filename");
        filename = "1.png";
        System.out.println(filename);


        //获取输入流
        ServletContext servletContext = getServletContext();
        //在回传前，通过响应头告诉客户端返回的数据类型
        String mimeType = servletContext.getMimeType("/file/" + filename);
        resp.setContentType(mimeType);
        System.out.println(mimeType);
        //告诉客户端收到的数据是用于下载使用
        if (req.getHeader("User-Agent").contains("Firefox")) {
            // 如果是火狐浏览器使用Base64编码
            resp.setHeader("Content-Disposition", "attachment; filename==?UTF-8?B?" + new BASE64Encoder().encode("中国.jpg".getBytes("UTF-8")) + "?=");
        } else {
            // 如果不是火狐，是IE或谷歌，使用URL编码操作
            resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("中国.jpg", "UTF-8"));
        }
        // 获取输入流
        InputStream resourceAsStream = servletContext.getResourceAsStream("/file/" + filename);

        // 获取输出流
        OutputStream outputStream = resp.getOutputStream();
        // 流的复制
        IOUtils.copy(resourceAsStream, outputStream);
    }
}
